package com.xjj.service.controller;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjj.entity.Parent;
import com.xjj.entity.ResponseEntity;
import com.xjj.service.feign.ManagerFeignClient;
import com.xjj.util.exception.BusinessException;
import com.xjj.util.utils.JwtUtil;
import com.xjj.util.utils.RegexUtils;
import com.xjj.vo.UserLoginVO;
import io.swagger.annotations.Api;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.xjj.util.utils.RedisConstants.*;


/**
 * @author : 王泰元
 * @date : 2022/10/27 14:17
 */
@Api(tags = "小程序登录相关接口")
@RestController
@RequestMapping("/auth/api/")
public class ApiLoginController {

    @Resource
    ManagerFeignClient managerFeignClient;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/login")
    public ResponseEntity<Parent> login(@RequestBody UserLoginVO loginVO, HttpServletResponse response) throws JsonProcessingException {
        // 1、校验手机号格式
        if (RegexUtils.isPhoneInvalid(loginVO.getTel())) {
            throw new BusinessException("手机号格式不正确");
        }

        // 2、从缓存中查询验证码，并校验验证码
        String cacheCode = (String) redisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginVO.getTel());
        if (StrUtil.isBlank(cacheCode) || !cacheCode.equals(loginVO.getCode())) {
            throw new BusinessException("验证码错误");
        }

        // 3、远程调用查询家长信息
        Parent parent = managerFeignClient.login(loginVO.getTel()).getData();
        if (parent == null) {
            throw new BusinessException("未查询到家长信息");
        }

        // 4、生成token
        // 生成 jwt
        parent.setPassword(null);
        String token = JwtUtil.createToken(new ObjectMapper().writeValueAsString(parent), "parent");

        // token 存到 redis ，有效期 30m
        redisTemplate.opsForValue().set(LOGIN_TOKEN_API_KEY + token, parent, LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        response.setHeader("token", token);

        response.setHeader("Access-Control-Expose-Headers", "*");

        return ResponseEntity.SUCCESS("登录成功", parent);
    }
}
